import {
  View,
  Text,
  StyleSheet,
  Image,
  ScrollView,
  StatusBar,
  Pressable,
  LayoutChangeEvent,
} from 'react-native'
import { useFocusEffect } from '@react-navigation/native'
import { flexCol } from '../../assets/style/common'
import useGetStatusBar from '../../utils/useGetStatusBar'
import { LinearGradient } from 'expo-linear-gradient'
import { CategoryData, GoodsData, subCategory } from '../../assets/data/data'
import Price from '../../component/price'
import SearchTxt from '../../component/searchTxt'
import { useState, useCallback, useMemo, useEffect, useRef } from 'react'
import { Shadow } from 'react-native-shadow-2'
import CustomFreshControl from '../../component/refreshControl/refreshControl'
const CategoryDataWrap = CategoryData.map(item => Object.assign({ x: 0 }, item))
export const msgProxy: { id: number } = {
  id: 0,
}
export default function Category({ navigation, route }: any) {
  const { categoryId } = route?.params || { categoryId: 1 }
  const [refreshing, setRefreshing] = useState(false)
  const cateScrollView = useRef<ScrollView>(null)
  const goodsScrollView = useRef<ScrollView>(null)
  const [cateData, setCateData] = useState(CategoryDataWrap)
  const [goodsData, setGoodsData] = useState(GoodsData)
  const [barHeight] = useGetStatusBar()
  const [currentCateId, setCurrentCateId] = useState(11) // 二级类型
  const [bigCurrentCateId, setBigCurrentCateId] = useState(categoryId) // 一级类型
  const [sort, setSort] = useState<
    'zonghe' | 'price-desc' | 'price-asc' | 'sale-desc' | 'sale-asc'
  >('zonghe') // 分类
  // 初始化
  useEffect(() => {
    msgProxy.id = categoryId
  }, [categoryId])
  const subCateData = useMemo(() => {
    const list = subCategory.filter(item => item.pid === bigCurrentCateId)
    if (list && list.length) {
      setCurrentCateId(list[0].id)
    }
    return list
  }, [bigCurrentCateId])
  // 从其他页面过来的
  useFocusEffect(
    useCallback(() => {
      msgProxy.id && setBigCurrentCateIdWithAnimal(msgProxy.id)
      msgProxy.id = 0
    }, [cateData]),
  )

  function onSubCate(id: number) {
    setCurrentCateId(id)
  }
  function onBigSubCate(id: number) {
    console.log('onBigSubCate,', id)
    setBigCurrentCateIdWithAnimal(id)
  }
  function setBigCurrentCateIdWithAnimal(
    id: number,
    scrollWithAnimation: boolean = true,
  ) {
    setBigCurrentCateId(id)
    const cate = cateData.find(item => item.id === id)
    cate &&
      cateScrollView.current?.scrollTo({
        x: cate.x - 50,
        animated: scrollWithAnimation,
      })
  }
  function onTopCategoryLayout(id: number, e: LayoutChangeEvent) {
    const x = e.nativeEvent.layout.x
    setCateData(arr =>
      arr.map(item => (item.id === id ? Object.assign({}, item, { x }) : item)),
    )
    if (id === bigCurrentCateId) {
      cateScrollView.current?.scrollTo({
        x: x - 50,
        animated: false,
      })
    }
  }
  function onPressAll() {
    navigation.push('CateGoryDrawer', { categoryId: bigCurrentCateId })
  }
  function onSort(type: string) {
    let newSort: typeof sort = 'zonghe'

    if (type === 'zonghe') {
      newSort = 'zonghe'
    } else if (type === 'price') {
      newSort = sort === 'price-desc' ? 'price-asc' : 'price-desc'
    } else {
      newSort = sort === 'sale-desc' ? 'sale-asc' : 'sale-desc'
    }
    if (newSort === 'zonghe') {
      setGoodsData(goodsData)
    } else {
      const cpData: typeof goodsData = JSON.parse(JSON.stringify(goodsData))
      cpData.sort((a, b) => {
        switch (newSort) {
          case 'price-desc':
            return a.price - b.price >= 0 ? -1 : 1
          case 'price-asc':
            return a.price - b.price >= 0 ? 1 : -1
          case 'sale-asc':
            return a.sale - b.sale >= 0 ? 1 : -1
          case 'sale-desc':
          default: {
            return a.sale - b.sale > 0 ? -1 : 1
          }
        }
      })
      setGoodsData(cpData)
    }
    setSort(newSort)

    goodsScrollView.current?.scrollTo({ y: 0 })
  }
  function goGoodDetail() {
    navigation.push('GoodDetail')
  }
  function onRefresh() {
    setRefreshing(true)
    setTimeout(() => {
      setRefreshing(false)
    }, 2000)
  }
  return (
    <View style={styles.container}>
      <StatusBar barStyle="light-content" />
      <LinearGradient
        start={{ x: 0.2, y: 0.5 }}
        end={{ x: 0.8, y: 0.5 }}
        colors={['#F0DFE2', '#F2EEDF']}
        style={StyleSheet.compose(styles.header, {
          height: 48 + barHeight + 76,
        })}
      >
        <LinearGradient
          start={{ x: 0.2, y: 0.5 }}
          end={{ x: 0.8, y: 0.5 }}
          colors={['#F0DFE2', '#F2EEDF']}
          style={{ paddingHorizontal: 12, position: 'relative', zIndex: 1 }}
        >
          <SearchTxt style={{ marginTop: barHeight + 4 }} />
        </LinearGradient>

        <View style={flexCol(styles.topCateList)}>
          <ScrollView
            horizontal
            style={styles.topCateScroll}
            showsHorizontalScrollIndicator={false}
            ref={cateScrollView}
          >
            {cateData.map(item => (
              <Pressable
                onLayout={e => onTopCategoryLayout(item.id, e)}
                key={item.id}
                onPress={() => onBigSubCate(item.id)}
                style={flexCol(styles.topCateItem)}
              >
                <View
                  style={[
                    styles.topCateIconWrap,
                    bigCurrentCateId === item.id &&
                      styles.topCateIconWrapActive,
                  ]}
                >
                  <Image style={styles.topCateIcon} source={item.icon} />
                </View>
                <View
                  style={[
                    styles.topCateTxtWrap,
                    bigCurrentCateId === item.id && styles.topCateTxtWrapActive,
                  ]}
                >
                  <Text
                    style={[
                      styles.topCateTxt,
                      bigCurrentCateId === item.id && styles.topCateTxtActive,
                    ]}
                  >
                    {item.txt}
                  </Text>
                </View>
              </Pressable>
            ))}
          </ScrollView>
          <Shadow offset={[-2, 0]} startColor="#00000010" distance={3}>
            <Pressable
              style={[styles.topAll, flexCol.default]}
              onPress={onPressAll}
            >
              <Text style={styles.topAllTxt}>全部</Text>
            </Pressable>
          </Shadow>
        </View>
      </LinearGradient>
      <View style={styles.scrollwrap}>
        <View style={styles.cateList}>
          {subCateData.map((item, index) => (
            <View
              onTouchEnd={() => onSubCate(item.id)}
              key={item.id}
              style={StyleSheet.compose(
                styles.lLine,
                currentCateId === item.id ? styles.lLineActive : {},
              )}
            >
              <LinearGradient
                start={{ x: 0.5, y: 0.1 }}
                colors={['#fed66f', '#ddf2fd']}
                end={{ x: 0.5, y: 0.9 }}
                style={StyleSheet.compose(styles.lSide, {
                  opacity: currentCateId === item.id ? 1 : 0,
                })}
              />
              {/* <Image style={styles.lIcon} source={item.icon}></Image> */}
              <Text style={styles.lTxt}>{item.txt}</Text>
              <View
                style={StyleSheet.compose(styles.lCoreRT, {
                  opacity: index !== 0 && currentCateId === item.id ? 1 : 0,
                })}
              >
                <View style={styles.lCoreRTInner} />
              </View>
              <View
                style={StyleSheet.compose(styles.lCoreRB, {
                  opacity:
                    index !== cateData.length - 1 && currentCateId === item.id
                      ? 1
                      : 0,
                })}
              >
                <View style={styles.lCoreRBInner} />
              </View>
            </View>
          ))}
        </View>
        <View style={styles.scrollContain}>
          <View style={flexCol(styles.condition)}>
            <Text style={styles.ctit} />
            <Pressable onPress={() => onSort('zonghe')} style={flexCol.default}>
              <Text
                style={StyleSheet.compose(
                  styles.cdt1,
                  sort === 'zonghe' ? styles.cdt1Active : {},
                )}
              >
                综合
              </Text>
            </Pressable>
            <Pressable onPress={() => onSort('price')} style={flexCol.default}>
              <Text
                style={StyleSheet.compose(
                  styles.cdt1,
                  sort.indexOf('price') >= 0 ? styles.cdt1Active : {},
                )}
              >
                价格
              </Text>
              <Image
                style={styles.cdtIcon1}
                source={
                  sort === 'price-desc'
                    ? require('../../assets/icon/sort-desc.png')
                    : sort === 'price-asc'
                      ? require('../../assets/icon/sort-asc.png')
                      : require('../../assets/icon/qiehuan.png')
                }
              />
            </Pressable>
            <Pressable onPress={() => onSort('sale')} style={flexCol.default}>
              <Text
                style={StyleSheet.compose(
                  styles.cdt1,
                  sort.indexOf('sale') >= 0 ? styles.cdt1Active : {},
                )}
              >
                销量
              </Text>
              <Image
                style={styles.cdtIcon1}
                source={
                  sort === 'sale-desc'
                    ? require('../../assets/icon/sort-desc.png')
                    : sort === 'sale-asc'
                      ? require('../../assets/icon/sort-asc.png')
                      : require('../../assets/icon/qiehuan.png')
                }
              />
            </Pressable>
          </View>
          <ScrollView
            ref={goodsScrollView}
            style={styles.scrollView}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <CustomFreshControl
                refreshing={refreshing}
                onRefresh={onRefresh}
              />
            }
          >
            {goodsData.map((item, index) => (
              <Pressable
                onPress={goGoodDetail}
                key={item.id}
                style={StyleSheet.compose(flexCol(styles.cardItem), {
                  marginTop: index === 0 ? 12 : 0,
                })}
              >
                <Image style={styles.gCover} source={item.cover} />
                <View style={{ flex: 1 }}>
                  <Text style={styles.gtit} numberOfLines={1}>
                    {item.title}
                  </Text>
                  <Price price={'' + item.price} />
                  <Text style={styles.gsale}>{item.sale}人已付款</Text>
                </View>
              </Pressable>
            ))}
          </ScrollView>
        </View>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  scrollwrap: {
    flex: 1,
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
  },
  container: {
    display: 'flex',
    flexDirection: 'column',
    height: '100%',
  },
  header: {
    height: 50,
    width: '100%',
    zIndex: 1,
    position: 'relative',
  },

  nptPhd: {
    flex: 1,
    fontSize: 12,
    color: '#999',
    lineHeight: 13,
  },

  topCateList: {
    height: 88,
    width: '100%',
  },
  topCateScroll: {
    flex: 1,
  },
  topCateItem: {
    marginLeft: 8,
    flexDirection: 'column',
    width: 60,
  },
  topCateIcon: {
    width: 24,
    height: 24,
    resizeMode: 'contain',
  },
  topCateIconWrap: {
    padding: 8,
    borderRadius: 18,
    borderWidth: 2,
    borderColor: '#fff',
  },
  topCateIconWrapActive: {
    borderColor: '#fed66f',
    backgroundColor: '#eef8fe',
  },
  topCateTxtWrap: {
    borderRadius: 10,
    marginTop: 4,
    width: 60,
    paddingVertical: 1,
  },
  topCateTxtWrapActive: {
    backgroundColor: '#fed66f',
  },
  topCateTxt: {
    fontSize: 14,
    color: '#666',
    width: 60,
    textAlign: 'center',
  },
  topCateTxtActive: {
    color: '#fff',
  },
  topAll: {
    width: 32,
    height: '100%',
    justifyContent: 'center',
    backgroundColor: '#F2EEDF',
  },
  topAllTxt: {
    paddingHorizontal: 6,
    color: '#333',
  },
  cateList: {
    width: 100,
    height: '100%',
    backgroundColor: '#f6f6f6',
  },
  lLine: {
    display: 'flex',
    paddingLeft: 12,
    paddingRight: 12,
    height: 64,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    position: 'relative',
  },
  lSide: {
    width: 4,
    borderRadius: 2,
    height: 18,
    position: 'absolute',
    left: 0,
    top: '50%',
    marginTop: -9,
  },
  lLineActive: {
    backgroundColor: '#ffffff',
  },
  lCoreRT: {
    position: 'absolute',
    right: 0,
    top: -16,
    width: 16,
    height: 16,
    backgroundColor: '#ffffff',
    transform: [
      {
        rotateZ: '180deg',
      },
    ],
  },
  lCoreRTInner: {
    width: 16,
    height: 16,
    backgroundColor: '#f6f6f6',
    borderTopLeftRadius: 16,
  },
  lCoreRB: {
    position: 'absolute',
    right: 0,
    bottom: -16,
    width: 16,
    height: 16,
    backgroundColor: '#fff',
    transform: [
      {
        rotateZ: '90deg',
      },
    ],
  },
  lCoreRBInner: {
    width: 16,
    height: 16,
    backgroundColor: '#f6f6f6',
    borderTopLeftRadius: 16,
  },
  lIcon: {
    width: 12,
    height: 12,
    marginRight: 8,
    resizeMode: 'contain',
  },
  lTxt: {
    fontSize: 14,
    color: '#666',
  },
  scrollContain: {
    height: '100%',
    flex: 1,
    backgroundColor: '#fff',
  },
  scrollView: {
    height: '100%',
  },
  condition: {
    backgroundColor: '#fff',
    height: 44,
    width: '100%',
    display: 'flex',
    flexDirection: 'row',
    paddingLeft: 12,
    paddingRight: 12,
  },
  cardItem: {
    backgroundColor: '#fff',
    marginBottom: 12,
    alignItems: 'flex-start',
  },
  gCover: {
    width: 78,
    height: 78,
    marginRight: 12,
    marginLeft: 12,
    borderRadius: 8,
    resizeMode: 'contain',
  },
  gtit: {
    marginTop: 4,
    marginBottom: 12,
  },
  gsale: {
    fontSize: 12,
    color: '#999',
    marginTop: 4,
  },
  ctit: {
    fontSize: 14,
    color: '#333',
    flex: 1,
  },
  cdt1: {
    fontSize: 12,
    color: '#666',
    width: 38,
    textAlign: 'right',
  },
  cdt1Active: {
    color: '#fb969a',
  },
  cdtIcon1: {
    width: 10,
    height: 10,
    resizeMode: 'contain',
    marginLeft: 2,
  },
  refresh: {
    position: 'absolute',
    zIndex: 2,
    height: 30,
    fontSize: 14,
    left: 0,
  },
})
